package com.lbd.smsplatform.service.impl;

import com.lbd.base.service.BaseServiceImpl;
import com.lbd.smsplatform.bean.SmsWhiteList;
import com.lbd.smsplatform.dao.SmsWhiteListRepository;
import com.lbd.smsplatform.service.SmsWhiteListService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * Created by wang on 2016/9/26.
 */
@Service
@Transactional
public class SmsWhiteListServiceImpl extends BaseServiceImpl<SmsWhiteList, SmsWhiteListRepository> implements SmsWhiteListService {

    private final Logger log = Logger.getLogger(this.getClass());
    @Autowired
    SmsWhiteListRepository smsWhiteListRepository;

    @Override
    public String buildJpql(SmsWhiteList smsWhiteList, Map<String, Object> parameter) {
        StringBuilder jpqlBuilder = new StringBuilder("  from  SmsWhiteList t   ");
        if (smsWhiteList != null) {
            if (StringUtils.isNotBlank(smsWhiteList.getRecipient())) {
                jpqlBuilder.append(" and  recipient like :recipient");
                parameter.put("recipient", "%" + smsWhiteList.getRecipient() + "%");
            }
        }
        return jpqlBuilder.toString();
    }

    @Override
    public List<SmsWhiteList> findByRecipient(String recipient) {
        return smsWhiteListRepository.findByRecipient(recipient);
    }

    @Override
    public SmsWhiteList findById(String id) {
        return smsWhiteListRepository.findOne(id);
    }


    @Override
    public void save(SmsWhiteList smsWhiteList) {
        List<SmsWhiteList> smsWhiteLists = smsWhiteListRepository.findByRecipient(smsWhiteList.getRecipient());
        if (smsWhiteLists.size() > 0) {
            SmsWhiteList SmsWhiteListExist = smsWhiteLists.get(0);
            BeanUtils.copyProperties(smsWhiteList, SmsWhiteListExist, "id", "createdDate");
            super.update(SmsWhiteListExist);
        } else {
            super.save(smsWhiteList);
        }

    }

    ;
}
